//
//  MZRecorder.swift
//  MZTool
//
//  Created by gby on 2023/1/29.
//

import Foundation
import AVFoundation

final public class MZRecorder: NSObject, AVAudioRecorderDelegate {
    private var audioRecorder: AVAudioRecorder?
    private var timer: MZTimer?
    private var update: (TimeInterval?) -> ()
    public let url: URL
    public init?(url: URL, update: @escaping (TimeInterval?) -> Void){
        self.update = update
        self.url = url
        super.init()
        do{
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)
            try AVAudioSession.sharedInstance().setActive(true)
            AVAudioSession.sharedInstance().requestRecordPermission { [weak self] allowed in
                if allowed {
                    self?.start(url)
                }else{
                    self?.update(nil)
                }
            }
        } catch{
            return nil
        }
    }
    
    private func start(_ url: URL) {
        let  setting: [String: Any] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
            AVSampleRateKey: 44100.0 as Float,
            AVNumberOfChannelsKey: 1
        ]
        if let recorder = try? AVAudioRecorder(url: url, settings: setting) {
            recorder.delegate = self
            audioRecorder = recorder
            recorder.record()
            timer = MZTimer.init { [weak self] _ , _ in
                self?.update(self?.audioRecorder?.currentTime)
                if let de = self?.audioRecorder?.averagePower(forChannel: 1) {
                    MZ.printLog("\(de)")
                }
            }
            timer?.start()
        }else{
            update(nil)
        }
    }
    
    public func stop() {
        audioRecorder?.stop()
        timer?.stop()
    }
    
    public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if flag {
            stop()
        }else{
            update(nil)
        }
        do{
            try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
        }catch{
            
        }
    }
    
    deinit {
        timer?.stop()
        timer = nil
    }
}
